/*- coding = utf-8 -*-
@Time : 2023/7/4 14:27
@Author : 管茂良
@File : index.ts
@web  : www.php-china.com
@Software: WebStorm
*/

import { h, ref, render} from "vue";
import uToast from "@/uni_modules/uview-plus/components/u-toast/u-toast.vue"
import {typeType} from "@/plugins/model/toast/types";

interface propsInterface{
    message:string,
    type?:typeType,
    duration?:number,
    position?:string,
    loading?:boolean,
    complete?:Function,
}
const parentNode = document.createElement('div')
parentNode.setAttribute("id","toast-style")
let optionsInit:propsInterface = {
    message:"",
    type:"default",
    duration:2000,
    position:"center",
    loading:false,
    complete:()=>{}
}
let options = ref<propsInterface>(optionsInit)

const handleToastRender = () => {
    // 创建 虚拟dom
    const boxVNode = h(uToast, {...options.value})
    // 将虚拟dom渲染到 container dom 上
    render(boxVNode, parentNode)
    // 最后将 container 追加到 body 上
    document.body.appendChild(parentNode)
    return boxVNode;
}

let modalInstance: any

const handleToast = () => {
    const show = (props:propsInterface)=>{
        if (modalInstance) {
            const toastVue = modalInstance.component
            // 调用上述组件中定义的open方法显示弹框
            // 注意不能使用toastVue.ctx来调用组件函数（build打包后ctx会获取不到）
            toastVue.proxy.show(props);
        } else {
            options.value = Object.assign(options.value,props)
            modalInstance = handleToastRender()
            show(options.value)
        }
    }
    const hide = ()=>{
        if (modalInstance) {
            const toastVue = modalInstance.component
            // 调用上述组件中定义的open方法显示弹框
            // 注意不能使用toastVue.ctx来调用组件函数（build打包后ctx会获取不到）
            toastVue.proxy.hide();
        } else {
            modalInstance = handleToastRender()
            hide()
        }
    }
    return {show,hide}
}

export default handleToast
